<template>
  <div class="box">
    <!-- 头部搜索模块 -->
    <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :addFun="addDrawerForm"
      :buttonList="buttonList" />
    <!-- 中间表格模块 -->
    <BaseTable :data="standardRatetableData" @details="dialogClick" :columns="standardRateDataColumns"
      :tableHeight="tableHeight" :pagination="false" :loading="loading"></BaseTable>
    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryAll.startpage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="queryAll.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="queryAll.totalNum"></el-pagination>
    </div>
    <!-- 新增编辑 -->
    <el-drawer :before-close="handleClose" :title="title" :visible.sync="drawerInner" direction="rtl" size="70%">
      <el-form label-position="top" label-width="100px" style="padding:10px 20px;" :rules="formRule" ref="formRef"
        :model="innerForm">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="费目名称" prop="rateItemCode">
              <el-select size="small" style="width: 100%" placeholder="选择业务费目名称" clearable
                v-model="innerForm.rateItemCode" v-selecttext="innerForm.rateItemName, rateList, 'rateItemCode'" @change="changeRateItem">
                <el-option v-for="(item, index) in rateList" :key="item.rateItemCode" :label="item.rateItemName"
                  :value="item.rateItemCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收费方">
              <el-select size="small" style="width: 100%" placeholder="请选择收费方" clearable
                v-model="innerForm.chargeCompanyId"
                v-selecttext="innerForm.chargeCompanyName, companyList, 'companyId', 'companyName'">
                <el-option v-for="(item, index) in companyList" :key="item.companyId" :label="item.companyName"
                  :value="item.companyId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付费方" prop="companyId">
              <el-select size="small" style="width: 100%" filterable clearable placeholder="请选择付费方"
                v-model="innerForm.companyId" v-selecttext="innerForm.companyName, companyList, 'companyId'">
                <el-option v-for="(item, index) in companyList" :key="item.companyId" :label="item.companyName"
                  :value="item.companyId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="贸别">
              <el-select size="small" style="width: 100%" v-model="innerForm.tradeType" clearable placeholder="请选择贸别">
                <el-option v-for="item in tradeTypeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货名">
              <el-select size="small" style="width: 100%" filterable multiple v-model="innerForm.cargoCode" clearable
                placeholder="请选择货名">
                <el-option v-for="item in cargoList" :key="item.cargoCode" :label="item.cargoName"
                  :value="item.cargoCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="作业过程">
              <el-select size="small" style="width: 100%" v-model="innerForm.processCode" clearable placeholder="请选择作业过程"
                v-selecttext="innerForm.processName, processData, 'processCode'">
                <el-option v-for="item in processData" :key="item.processCode" :label="item.processName"
                  :value="item.processCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单价（元）" prop="rate">
              <el-input-number style="width: 100%" size="small" v-model="innerForm.rate" :precision="2" :step="0.01"
                :max="999999" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率" prop="tax">
              <el-input-number style="width: 100%" size="small" v-model="innerForm.tax" :precision="2" :step="0.01"
                :max="999999" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计费单位" prop="unitCode">
              <el-select size="small" style="width: 100%" v-model="innerForm.unitCode" clearable placeholder="请选择计费单位">
                <el-option v-for="item in billingList" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="有效期" :required="true">
              <el-date-picker style="width: 100%;" size="small" v-model="dateList" value-format="yyyy-MM-dd"
                type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="起始区域" prop="startRegionCode">
              <el-select style="width: 100%" size="small" v-model="innerForm.startRegionCode" clearable
                placeholder="请选择起始区域" v-selecttext="innerForm.startRegionName, regionList, 'dictValue', 'dictLabel'">
                <el-option v-for="item in regionList" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="终点区域" prop="endRegionCode">
              <el-select style="width: 100%" size="small" v-model="innerForm.endRegionCode" clearable
                placeholder="请选择终点区域" v-selecttext="innerForm.endRegionName, regionList, 'dictValue', 'dictLabel'">
                <el-option v-for="item in regionList" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="装卸" prop="loadUnload">
              <el-select style="width: 100%" size="small" v-model="innerForm.loadUnload" clearable placeholder="请选择装卸">
                <el-option v-for="item in loadUnloadList" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提单方大于一万" prop="isMax">
              <el-select style="width: 100%" size="small" v-model="innerForm.isMax" clearable placeholder="请选择">
                <el-option v-for="item in isMaxList" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="showFlag">
            <el-form-item label="节数" prop="nodes">
              <el-input-number style="width: 100%" size="small" v-model="innerForm.nodes" :precision="0" :step="1"
                :max="99" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="备注" prop="remark">
              <el-input size="small" maxlength="500" type="textarea" :autosize="{ minRows: 2, maxRows: 3 }"
                placeholder="请输入备注且最多500个字" v-model="innerForm.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button type="primary" @click="submitInner()" size="small" :loading="ineerLoading">
          {{ ineerLoading ? "提交中 ..." : "保 存" }}
        </el-button>
        <el-button size="small" @click="drawerInner = false">取消</el-button>
      </div>
    </el-drawer>
    <!-- 中止弹窗 -->
    <el-dialog title="请输入中止日期" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form label-width="80px" :model="stopDate">
        <el-form-item label="终止日期">
          <el-date-picker v-model="stopDate.susDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import dfilters from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/billingSettlementSys/standardRate'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
export default {
  name: 'reportingReview',
  components: {
    BaseTable,
    headerSearch
  },
  data() {
    return {
      menuFlag: false,
      oldOut: {},
      oldInner: {},
      menuData: [],
      ineerLoading: false,
      tableHeight: window.innerHeight - 200,
      // 搜索框显示对象
      selectObject: [
        {
          name: '费目',
          type: 'select',
          modelName: 'rateItemCode',
          selectLabel: 'rateItemName',
          selectValue: 'rateItemCode',
          selectData: []
        }
        // {
        //     name: '选择状态',
        //     type: 'select',
        //     modelName: 'status',
        //     selectData: [
        //         {
        //             dictValue: '1',
        //             dictLabel: '未审核'
        //         }, {
        //             dictValue: '2',
        //             dictLabel: '已审核'
        //         },
        //     ],
        //     selectLabel: 'dictLabel',
        //     selectValue: 'dictValue'
        // }
      ],
      // 按钮的list
      buttonList: [
        { label: '新建', type: 'primary', icon: 'el-icon-plus', click: () => this.addDrawerForm, permission: 'costDataSubsystem:rate:insert' },
        { label: '中止', type: 'primary', icon: 'el-icon-switch-button', click: () => this.stopClick, permission: 'costDataSubsystem:rate:break' }
      ],
      rateList: [],
      companyList: [],
      processData: [],
      cargoList: [],
      billingList: [],
      regionList: [],
      loadUnloadList: [
        {
          dictValue: '装',
          dictValue: '装'
        }, {
          dictValue: '卸',
          dictValue: '卸'
        }
      ],
      isMaxList: [
        {
          dictValue: 'Y',
          dictLabel: '是'
        }, {
          dictValue: 'N',
          dictLabel: '否'
        }
      ],
      tradeTypeList: [
        {
          value: '内贸',
          label: '内贸'
        },
        {
          value: '外贸',
          label: '外贸'
        }
      ],
      title: '',
      standardRateDataColumns: [ // table表头
        { prop: 'rateItemName', label: '费目' },
        { prop: 'chargeCompanyName', label: '收费方', isShort: true },
        { prop: 'companyName', label: '付费方', isShort: true },
        { prop: 'processName', label: '作业过程', isShort: true },
        { prop: 'tradeType', label: '贸别' },
        { prop: 'cargoName', label: '货名' },
        { prop: 'tax', label: '税率' },
        { prop: 'rate', label: '单价', isMoney: true },
        { prop: 'unitCode', label: '计费单位' },
        { prop: 'loadUnload', label: '装卸' },
        { prop: 'nodes', label: '节数' },
        {
          prop: 'isMax',
          label: '提单方大于一万',
          width: 150,
          render(h, params) {
            let text = ''
            if (params.row.isMax) {
              text = params.row.isMax == 'Y' ? '是' : '否'
            }
            return h('span', {
              domProps: {
                innerHTML: text
              }
            })
          }
        },
        {
          prop: 'endDate',
          label: '有效期',
          width: 150,
          render: (h, param) => {
            return h('span', {
              domProps: {
                // 添加标签,使用自己引入的iconfont图标
                innerHTML:
                  param.row.endDate = param.row.startDate + '~' + param.row.endDate
              }
            })
          }
        },
        { prop: 'susDate', label: '中止日期' },
        { prop: 'remark', label: '备注' },
        {
          label: '操作',
          width: 200,
          fixed: 'right',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              {
                calss: 'btnClass'
              },
              [
                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: params.row.delFlag == '1'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#0B6CD6;' v-if="menuArr.includes('修改标准费率')"><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleEdit(params.$index, params.row)
                    }
                  }
                }),

                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    // innerHTML: `<i class="iconfont icon-tubiao_liebiaoshanchu" style="color:#DA2821"></i> 删除`
                    innerHTML: `<span style='color:#F75E5E;' v-if="menuArr.includes('删除标准费率')"><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleDelete('1', params.row.id)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      standardRatetableData: [],
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        totalNum: 0,
        rateItemCode: ''
      },
      drawerOut: false,
      flagOut: true,
      outForm: {
        portName: '',
        portCode: '',
        logogram: '',
        nationCode: '',
        sortNum: ''
      },
      drawerInner: false,
      innerForm: {
        rateItemCode: '',
        rateItemName: '',
        chargeCompanyId: '',
        chargeCompanyName: '',
        companyId: '',
        companyName: '',
        tradeType: '',
        cargoCode: [],
        cargoName: [],
        processCode: '',
        processName: '',
        nodes: 0,
        rate: '',
        tax: '',
        unitCode: '',
        startDate: '',
        endDate: '',
        startRegionCode: '',
        startRegionName: '',
        endRegionCode: '',
        endRegionName: '',
        loadUnload: '',
        isMax: '',
        remark: ''
      },
      dateList: [],
      formRule: {
        rateItemCode: [
          { required: true, message: '费目名称不能为空' }
        ],
        rate: [
          { required: true, message: '单价不能为空' }
        ],
        tax: [
          { required: true, message: '税率不能为空' }
        ],
        unitCode: [
          { required: true, message: '计费单位不能为空' }
        ]
      },
      dialogVisible: false,
      stopDate: {
        id: '',
        susDate: '',
        tax: '',
        rate: '',
        startDate: '',
        endDate: ''
      },
      showFlag: false
    }
  },
  async activated() {
    var menuArr = []
    var menuId = ''
    if (localStorage.getItem('menuArr')) {
      menuArr = JSON.parse(localStorage.getItem('menuArr'))
    }
    menuArr.map(item => {
      item.children.map(v => {
        if (window.location.href.includes(v.url)) {
          menuId = v.id
        }
      })
    })
    if (menuId) {
      await publicapi
        .getPermissionsBtn(menuId)
        .then(res => {
          res.data.data.map(item => {
            this.menuData.push(item.RESOURCENAME)
          })
        })
        .catch(() => { })
    }
    if (this.$store.state.app.searchResouce === 'menu') {
      this.getlistRateItem()
      this.getComp()
      this.getProcessList()
      this.getListCargo()
      this.getlistBillingUnit()
      this.getRegionData()
      this.menuFlag = true
    }
  },
  methods: {
    // 获取费目
    getlistRateItem() {
      publicapi.getlistRateItem().then(res => {
        this.rateList = res.data.data
        this.selectObject[0].selectData = this.rateList
      })
    },
    /**
     * 获取收费方付费方
     */
    async getComp() {
      const res = await publicapi.getListComp()
      this.companyList = res.data.data
    },
    /**
         * 获取作业过程
         */
    async getProcessList() {
      const res = await publicapi.getlistProcess({ mainType: '1' })
      this.processData = res.data.data
    },
    // 获取货名
    getListCargo() {
      publicapi.getListCargo().then(res => {
        this.cargoList = res.data.data
      })
    },
    // 获取计费单位
    getlistBillingUnit() {
      publicapi.getDictData('BILLING_UNIT').then(res => {
        this.billingList = res.data.data.BILLING_UNIT
      })
    },
    // 字典查询所属区域
    async getRegionData() {
      const res = await publicapi.getDictData('REGION')
      this.regionList = res.data.data.REGION
    },
    // 获取表格数据
    async getData() {
      this.loading = true
      await api.getData(this.queryAll).then(res => {
        if (res.status == '200') {
          this.standardRatetableData = res.data.data.pages
          this.standardRatetableData.map(item => {
            item.susDate ? item.susDate = dfilters.getProcessingDate(item.susDate, '3') : item.susDate = ''
            item.unitCode ? item.unitCode = this.billingList.filter(v => v.dictValue == item.unitCode)[0].dictLabel : item.unitCode = ''
            item.startDate ? item.startDate = dfilters.getProcessingDate(item.startDate, '3') : item.startDate = ''
            item.endDate ? item.endDate = dfilters.getProcessingDate(item.endDate, '3') : item.endDate = ''
          })
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.queryAll.totalNum = res.data.data.totalNum
          this.loading = false
        }
      })
    },
    /**
         * 新建
         */
    addDrawerForm() {
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      this.title = '新建费率'
      this.innerForm = this.$options.data().innerForm
      this.showFlag = false
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
      this.dateList = []
    },
    // 修改按钮
    async handleEdit(index, row) {
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      this.showFlag = false
      this.dateList = []
      this.title = '修改费率'
      await api.getDataById(row.id).then(res => {
        if (res.status == '200') {
          this.innerForm = res.data.data
          this.dateList.push(this.innerForm.startDate)
          this.dateList.push(this.innerForm.endDate)
          if (this.innerForm.cargoCode) {
            this.innerForm.cargoCode = this.innerForm.cargoCode.split(',')
          }
          if (this.innerForm.nodes) {
            this.showFlag = true
          }
        }
      })
    },
    // 修改费目名称
    changeRateItem(val){
      this.innerForm.nodes = 0
      if(val){
        if(val == 'TXF'){
          this.showFlag = true
        }else{
          this.showFlag = false
        }
      }
    },
    /**
         * 新建、编辑保存
         */
    submitInner() {
      if (!this.dateList) {
        return this.$message.warning('请输入有效期')
      }
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.innerForm.startDate = this.dateList[0]
          this.innerForm.endDate = this.dateList[1]
          this.innerForm.cargoName = []
          if (this.innerForm.cargoCode) {
            if (this.innerForm.cargoCode.length > 0) {
              this.innerForm.cargoCode.forEach(item => {
                this.innerForm.cargoName.push(this.cargoList.filter(i => i.cargoCode == item)[0].cargoName)
              })
            } else {
              this.innerForm.cargoCode = ''
            }
          }

          const form = JSON.parse(JSON.stringify(this.innerForm))
          if (form.cargoName.length > 0) {
            form.cargoName = form.cargoName.join()
            form.cargoCode = form.cargoCode.join()
          } else {
            form.cargoName = ''
          }

          if (this.title == '新建费率') {
            api.addData(form).then(res => {
              if (res.status == '200') {
                this.getData()
                this.drawerInner = false
                this.$message.success(res.data.msg)
              }
            })
          } else {
            api.updateData(form).then(res => {
              if (res.status == '200') {
                this.getData()
                this.drawerInner = false
                this.$message.success(res.data.msg)
              }
            })
          }
        }
      })
    },
    // 选中数据
    dialogClick(val) {
      this.stopDate = this.$options.data().stopDate;
      if (!this.stopDate.id) {
        this.stopDate.id = val.id
        this.stopDate.susDate = val.susDate
        this.stopDate.tax = val.tax
        this.stopDate.rate = val.rate
        this.stopDate.startDate = val.startDate
        this.stopDate.endDate = val.endDate
      }
    },
    // 中止按钮
    stopClick() {
      if (!this.stopDate.id) {
        return this.$message.warning('请选择一条数据')
      }
      if (!this.dialogVisible) {
        this.dialogVisible = true
      }
    },
    // 保存中止日期
    async saveAdd() {
      if (new Date(this.stopDate.startDate).getTime() <= new Date(this.stopDate.susDate).getTime() && new Date(this.stopDate.susDate).getTime() <= new Date(this.stopDate.endDate).getTime()) {
        await api.updateData(this.stopDate).then(res => {
          if (res.status == '200') {
            this.getData()
            this.dialogVisible = false
            this.$message.success(res.data.msg)
          }
        })
      } else {
        return this.$message.warning('终止日期必须在有效期内')
      }
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.stopDate = this.$options.data().stopDate;
      this.getData()
    },
    async handleDelete(val, id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteData(id).then(res => {
          if (res.data.code === '0000') {
            this.getData()

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getData()
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.drawerOut) {
        oldV = this.oldOut
        newV = this.outForm
      }
      if (this.drawerInner) {
        oldV = this.oldInner
        newV = this.innerForm
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.selectBox {
  justify-content: space-between;
  display: flex;
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-bottom: 0;
  border-left: none;
  height: 50px;
  position: relative;
  align-items: center;
  padding-left: 14px;
  padding-right: 20px;
}

.input_box {
  display: flex;
}

.page {
  background: #ffffff;
  text-align: right;
  border-radius: 0 0 4px 4px;
  padding: 5px 20px;
}

/deep/.el-tabs--border-card>.el-tabs__content {
  padding: 0 !important;
}

//抽屉底部样式
/deep/ .el-drawer__header {
  margin-bottom: 0;
  padding: 16px;
  border-bottom: 1px solid gainsboro;
}

.demo-drawer__footer {
  text-align: right;
  padding-right: 20px;
  border-top: 1px solid #c8cfde;
  background-color: #f5f7fa;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  line-height: 50px;
}

.box {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-radius: 4px 4px 0 0;
  border-top: none;
}

/deep/.el-drawer__body {
  margin-bottom: 30px;
}
</style>
